#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath "$(dirname "$0")")
. "${test_dir}/../functions"

create_namespace "$namespace"
deploy_operator

deploy_minio

desc 'create first PSMDB cluster'
cluster="some-name"
kubectl_bin apply \
    -f "$conf_dir/cloud-secret.yml" \
    -f "$conf_dir/minio-secret.yml" \
    -f "$conf_dir/secrets.yml" \
    -f "$conf_dir/client.yml"

apply_cluster "$test_dir/conf/$cluster-rs0.yml"
desc 'check if all 3 Pods started'
wait_for_running $cluster-rs0 3
wait_for_running $cluster-cfg 3 "false"

desc 'check if service and statefulset created with expected config'
compare_kubectl statefulset/$cluster-rs0
compare_kubectl statefulset/$cluster-cfg
compare_kubectl deployment/$cluster-mongos ""

desc 'write data, read from all'
run_mongos \
    'db.createUser({user:"myApp",pwd:"myPass",roles:[{db:"myApp",role:"readWrite"}]})' \
    "userAdmin:userAdmin123456@$cluster-mongos.$namespace"
sleep 2
run_mongos \
    'use myApp\n db.test.insert({ x: 100500 })' \
    "myApp:myPass@$cluster-mongos.$namespace"
sleep 10 # for minikube
compare_mongos_cmd "find" "myApp:myPass@$cluster-mongos.$namespace"

wait_backup_agent $cluster-rs0-0
wait_backup_agent $cluster-rs0-1
wait_backup_agent $cluster-rs0-2

backup_name_aws="backup-aws-s3"
backup_name_minio="backup-minio"
backup_name_gcp="backup-gcp-cs"

desc 'run backups'
run_backup aws-s3
run_backup minio
run_backup gcp-cs

wait_backup "$backup_name_aws"
wait_backup "$backup_name_minio"
wait_backup "$backup_name_gcp"

sleep 5

desc 'check backup and restore -- aws-s3'
backup_dest_aws=$(get_backup_dest "$backup_name_aws")
curl -s "https://s3.amazonaws.com/operator-testing/${backup_dest_aws}_rs0.dump.gz" | gunzip >/dev/null
run_restore $backup_name_aws 3 1 "-mongos"
wait_restore $backup_name_aws 3 1 "-mongos"

desc 'check backup and restore -- minio'
backup_dest_minio=$(get_backup_dest "$backup_name_minio")
kubectl_bin run -i --rm aws-cli --image=perconalab/awscli --restart=Never -- \
    /usr/bin/env AWS_ACCESS_KEY_ID=some-access-key AWS_SECRET_ACCESS_KEY=some-secret-key AWS_DEFAULT_REGION=us-east-1 \
    /usr/bin/aws --endpoint-url http://minio-service:9000 s3 ls "s3://operator-testing/${backup_dest_minio}" |
    grep "${backup_dest_minio}_rs0.dump.gz"
run_restore $backup_name_minio 3 1 "-mongos"
wait_restore $backup_name_minio 3 1 "-mongos"

desc 'check backup and restore -- gcp-cs'
backup_dest_gcp=$(get_backup_dest "$backup_name_gcp")
curl -s "https://storage.googleapis.com/operator-testing/${backup_dest_gcp}_rs0.dump.gz" | gunzip >/dev/null
run_restore $backup_name_gcp 3 1 "-mongos"
wait_restore $backup_name_gcp 3 1 "-mongos"

destroy "$namespace"
